<?
//Überprüfen ob der Abruf über die Hauptseite erfolgt
if(!defined('InStern')) exit;
//ini_set("memory_limit","32M");
ini_set("max_execution_time",360);
include("class/btsunfile.class.php");
include("class/filebox.class.php");
include("class/ftpfilebox.class.php");

function folderbackup($folder){
	$debug=true;
    $dir=$folder;
	if($debug) echo "folderbackup($dir)\n";

	if (is_dir($dir)) {
		if($debug) echo "öffne $dir\n";
		if($dh = opendir($dir)) {
        while($file = readdir($dh)){
			if($debug) echo "behandle $file ";
			if(substr($file,0,1)=="."){
				if($debug) echo "als empty \n";
			}elseif(is_dir($dir . $file)){
				if($debug) echo "als Ordner\n";
				$files=folderbackup($dir . $file."/");
				settype($files,"array");
				foreach($files as $store){
					$btsun[][file]=$store;
				}
			}else{
				if($debug) echo "als Datei\n";
			    $store[name]=$file;
				$store[path]=$dir;
				$store[content]=file_get_contents($dir . $file);
				$btsun[][file]=$store;
			}
        }
        closedir($dh);
    }
	return $btsun;
}


}

//######################################################## STRUCTURE IMPORT/EXPORT
if($_POST['do']=="import"){
    move_uploaded_file($_FILES[datei][tmp_name], "tmp/import.btsun");
	$file=new btsunfile("tmp/import.btsun");
	$file->setDB($db);
	if(!$file->check()){
		echo "<div class=\"error\">Not a valid btsun file!!!</div>";
		$file->debug();
		
	}else{	    
		$changes=$file->checkStructure();
		echo "
		<div class=\"info\">
			<b>The following changes will be made:</b>
			<pre>$changes</pre>
			<center><a href=\"index.php?page=admin&adminpage=backup&confirmimport=true\">confirm</a>
		</div>";		
	}
}
if($_GET['confirmimport']=="true"){
	$file=new btsunfile("tmp/import.btsun");
	$file->setDB($db);
	if(!$file->check()){
		echo "<div class=\"error\">Not a valid btsun file</div>";
	}else{	    
		$changes=$file->setStructure();
		echo "<div class=\"info\">
			<b>The following changes has been made:</b>
			<pre>$changes</pre>
		</div>";		
	}
}
//######################################################## Backup
if($_POST['do']=="backup"){
    $log="Starting procedure at ".date("d.m.Y - H:i:s")."\n";
    //Write filecontainer
    unset($btsun);
    $info[date]=date(U);
	$info[author]=$_SESSION[user][Name];
	$info[version]=$config[version];
    $btsun[][info]=$info;
    unset($info);
    //Database-Backup
    if(count($_POST[sqltables]>0)){
        $log.="Starting Database-Backup:\n";
        foreach($_POST[sqltables] as $table){
            $log.=date("H:i:s").": Table $table:\n";
            $sql[content]=$db->backup($table);            
            $log.=date("H:i:s").": -> content fetched\n";
            $sql[hash]=md5(serialize($sql[content]));
            $sql[structure]=md5(serialize($db->getStructure($table)));
			$sql[name]=$table;
            $log.=date("H:i:s").": -> structure/hash fetched\n";
            $btsun[][sql]=$sql;
            $log.=date("H:i:s").": -> stored to backup file\n";         
        }
    }
    //File-System Backup
    if(false){
        $log.="Starting File-System-Backup:";
		$files=folderbackup("data/");
		foreach($files as $store){
			$btsun[][file]=$store;
		}
    }
    //Creating Info
	$btsun[0][info][log]=$log;
    file_put_contents("tmp/backup.btsun", serialize($btsun));
	$backupname=$_REQUEST[name].".btsun";
	//print_r($btsun);
    unset($btsun);
	$copybackup=true;
}

?>
<h2>Backupsystem</h2>

<fieldset>
    <legend>
        <b>Available Backups:</b>
        <select onchange="location.href='index.php?page=admin&adminpage=backup&setftp='+this.value;">
            <option value="">local</option>
            <?
            //save change
            if(isset($_GET[setftp])){
                $_SESSION[ftp]=intval($_GET[setftp]);
            }
            foreach($config_ftp as $ftp_id => $ftp_value){
                if($_SESSION[ftp]==$ftp_id){
                    echo "
                    <option value=\"$ftp_id\" selected=\"selected\">$ftp_value[name]</option>";
                }else{
                    echo "
                    <option value=\"$ftp_id\">$ftp_value[name]</option>";
                }   
            }
        ?>
        </select>
	</legend>
	<?
	//selection between local and ftp
	if($_SESSION[ftp]==0){
		$fb=new filebox("backups");
		$fb->open("backup");
	}else{
		$id=$_SESSION[ftp];
		$fb=new ftpfilebox("backups");
		$fb->open($config_ftp[$id][host], $config_ftp[$id][user], $config_ftp[$id][pass], $config_ftp[$id][path]);
	}
	//Session ist offen
	if($copybackup){
		$fb->savefile("tmp/backup.btsun", $backupname);
	}
	if($_REQUEST['do']=="restore"){
		//copy backupfile to temp directory
		$fb->loadfile($_REQUEST[backup], "tmp/restore.btsun");
		//loading file
		$file=new btsunfile("tmp/restore.btsun");
		$file->setDB($db);
		$info=$file->info();

		echo "
		<div class=\"info\" style=\"text-align:left;\">
			<b>The following BTSUN-Backupfile will be restored</b><br>
			Backup from ".date("d.m.Y - H:i:s", $info[date])." created by $info[author] with Version $info[version]<br>".
			nl2br($file->restore(true))."
			<br>
			<input type=\"button\" value=\"confirm\" onclick=\"location.href='index.php?page=admin&adminpage=backup&do=confirmrestore';\" />
		</div>";		
    }
	if($_REQUEST['do']=="confirmrestore"){
		//loading file
		$file=new btsunfile("tmp/restore.btsun");
		$file->setDB($db);
		$info=$file->info();
		echo "
		<div class=\"info\" style=\"text-align:left;\">
			<b>The BTSUN-Backupfile has been successfully restored</b><br>".
			nl2br($file->restore())."
		</div>";		
    }
	if($_REQUEST['do']==erase){
		$fb->erase($_REQUEST[backup]);
	}
	$fb->setFilter("btsun");	
	echo $fb->html();
	
	//close connection
	$fb->close();
	echo "    
</fieldset>";

//Neues Backup erstellen {Formular}
//Backupnamen finden
$name="manual_backup_".date("d_m_Y");
if(file_exists("backup/".$name.".bak"))
{
  for($i=2; file_exists("backup/".$name."-".$i.".bak"); $i++) {}
  $name=$name."-".$i;
}

echo "
<fieldset>
    <legend>Create new Backup</legend>
    <form action=\"$_SERVER[PHP_SELF]\" method=\"post\">
        <table>
            <tr>
                <th>Database</th>
                <th>File-System</th>
                <th>Important Notice</th>
            </tr>
            <tr>
                <td>
                    <select name=\"sqltables[]\" size=\"6\"  multiple=\"multible\" style=\"width:200px\">";
                        $result = $db->list_tables();
                        while ($row = mysql_fetch_row($result)){
                            echo " 
                            <option value=\"$row[0]\" selected=\"selected\">$row[0]</option>";
                        }
                        echo "
                    </select>
                </td>
                <td>
                    <select name=\"filepacks\" size=\"6\" multiple style=\"width:200px\">
                        <option>userpics</option>
                        <option>uploads</option>
                        <option>tickets</option>
                        <option>kommander</option>
                    </select>
                </td>
                <td>Database and Filesystems backups are not recommendet in heavy use hours. The database connection will <u>not be closed</u> during the backup procedure, so it is possible that the databasebackup gets corrupted.</td>
            </tr>";
			if(intval(ini_get("memory_limit"))<515){
			    echo "<tr><td colspan=\"3\">The memory-limit configuration of the server is too low (".ini_get("memory_limit")."). A filesystem backup will be aborted</td></tr>";
		    }
			echo "
            <tr>
                <td colspan=\"2\">
                    <input type=\"hidden\" name=\"page\" value=\"$_SESSION[page]\" />
                    <input type=\"hidden\" name=\"adminpage\" value=\"$_SESSION[adminpage]\" />
                    <input type=\"hidden\" name=\"do\" value=\"backup\" />
                    <b>Backupname:</b><br>
                    <nobr><input type=\"text\" name=\"name\" value=\"$name\" size=\"40\"/>.btsun </nobr>
                </td>
                <td align=\"right\">
                    <input type=\"submit\" value=\"create backup\" />
                </td>
            </tr>
        </table>
    </form>
</fieldset>";



//Structure
echo "
<fieldset>
  <legend>Structure</legend>
    <table width=\"100%\">
	  <tr>
		<td align=\"right\"> 
		  <b>Import:</b>
		</td>
	    <td align=\"left\">
          <form action=\"$_SERVER[PHP_SELF]\" method=\"post\" enctype=\"multipart/form-data\">
            <input type=\"hidden\" name=\"do\" value=\"import\" />
            <input name=\"datei\" type=\"file\" size=\"10\" maxlength=\"100000\" onchange=\"this.form.submit();\"/>
          </form>
		</td>
		<td align=\"right\"> 
		  <b>Export:</b>
		</td>
		<td align=\"left\">
          <input type=\"button\" value=\"export\" onclick=\"location.href='index.php?page=admin&adminpage=backup&do=export';\" />";
          //Exportieren
          if($_GET['do']=="export"){
              unset($structure);
			  $result = $db->list_tables($config_db_name);
			  //create info
			  $info[date]=date(U);
			  $info[author]=$_SESSION[user][Name];
			  $info[version]=$config[version];
			  $btsun[][info]=$info;
              while ($row = $db->fetch_row($result)){
			      $structure[name]=$row[0];
				  $structure[content]=$db->getStructure($row[0]);
				  $structure[hash]=md5(serialize($structure[content]));
				  $btsun[][structure]=$structure;
              } 
              $db->free_result($result);
              file_put_contents("tmp/dbstructure.btsun", serialize($btsun));
  		      echo "<a href=\"tmp/dbstructure.btsun\">download</a>";  
          }
          echo "
		</td>
	  </tr>
	</table>
</fieldset>"; 

 